import React from "react";
import classNames from 'classnames';
import omit from 'omit.js';
import ZPlayer from './ZPlayer';

const events = [
    "abort", "canplay", "canplaythrough",
    "durationchange", "emptied", "ended",
    "error", "loadeddata", "loadedmetadata",
    "loadstart", "mozaudioavailable", "pause",
    "play", "playing", "progress", "ratechange",
    "seeked", "seeking", "stalled", "suspend",
    "timeupdate", "volumechange", "waiting",
    "screenshot", "thumbnails_show", "thumbnails_hide",
    "contextmenu_show", "contextmenu_hide", "notice_show",
    "notice_hide", "quality_start", "quality_end",
    "destroy", "resize", "fullscreen", "fullscreen_cancel"
];
const capitalize = function (str) {
    return `${str.charAt(0).toUpperCase()}${str.substring(1)}`;
};
const capitalizeEventName = function (str) {
    return str.split('_').map(capitalize).join('');
};
const eventsProps = events.map(eventName => ({ eventName, prop: `on${capitalizeEventName(eventName)}` }))

class ZPlayerComponent extends React.Component {

    constructor(props, context) {
        super(props, context);
    }

    componentDidMount() {
        let { onLoad, options } = this.props;
        //new player
        const player = this.dp = new ZPlayer({
            ...Object.assign({}, {
                lang: 'zh-cn',
                contextmenu: [
                ],
            }, options),
            container: this.container
        });
        //run load
        onLoad && onLoad(player);
        //bind player events
        eventsProps.forEach(({ eventName, prop }) => {
            if (prop in this.props) {
                player.on(eventName, this.props[prop])
            }
        })
    }

    render() {
        const { className, ...otherProps } = this.props;
        const resetProps = omit(otherProps, ['options', 'onLoad', ...eventsProps.map(ev => ev.prop)])
        const wrapperClassName = classNames({
            [`dplayer`]: true,
            [`${className}`]: !!className,
        });
        return <div ref={ref => this.container = ref} className={wrapperClassName} {...resetProps} />;
    }
}

export default ZPlayerComponent;